﻿using B.S.Filtration.Domain;
using B.S.Filtration.ErrorCode;
using B.S.Filtration.Read.Api.Application.Command.ProcessCommand;
using MediatR;
using SqlSugar;

namespace B.S.Filtration.Read.Api.Application.CommandHander.ProcessHandler
{
    public class GetProcessTypeCommandHandler : IRequestHandler<GetProcessTypeCommand, APIResult<APIPaging<ProcessType>>>
    {
        private readonly ISqlSugarClient db;

        public GetProcessTypeCommandHandler(ISqlSugarClient db)
        {
            this.db = db;
        }

        public async Task<APIResult<APIPaging<ProcessType>>> Handle(GetProcessTypeCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<ProcessType>> result = new APIResult<APIPaging<ProcessType>>();
            result.code = APIResultCode.success;
            result.msg = "查询显示成功";

            var list = db.Queryable<ProcessType>();

            int TotalCount = list.Count();
            int TotalPage = (int)Math.Ceiling(TotalCount * 1.0 / request.PageSize);
            list = list.OrderByDescending(p => p.Sort).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            APIPaging<ProcessType> paging = new APIPaging<ProcessType>();
            paging.TotalCount = TotalCount;
            paging.TotalPage = TotalPage;
            paging.list = list.ToList();

            result.data = paging;

            return await Task.FromResult(result);
        }
    }
}
